import datetime
import json
import os

import requests

from request_config import request_header, request_url_x_bogus


def get_user_post(__sec_user_id, __max_cursor):
    url = "https://www.douyin.com/aweme/v1/web/aweme/post/?device_platform=webapp&aid=6383&" \
          "channel=channel_pc_web&" \
          "sec_user_id=" + str(
        __sec_user_id) + "&max_cursor=" + str(
        __max_cursor) + "&locate_query=false&show_live_replay_strategy=1&need_time_list=1&time_list_query=0&whale_cut_token=&cut_version=1&count=18&publish_video_strategy_type=2&pc_client_type=1&version_code=170400&version_name=17.4.0&cookie_enabled=true&screen_width=1440&screen_height=900&browser_language=zh-CN&browser_platform=MacIntel&browser_name=Chrome&browser_version=118.0.0.0&browser_online=true&engine_name=Blink&engine_version=118.0.0.0&os_name=Mac+OS&os_version=10.15.7&cpu_core_num=8&device_memory=8&platform=PC&downlink=10&effective_type=4g&round_trip_time=50&webid=7235177582601504311&msToken=dKeqx26dkPVM6uiXEaCFw2Ay3OuYFvtwss8f_5XlmkCEa2xO0wryZRGgAtUnspXnXpFuWGcvwtd875d6FPTtPNtn-4T7bLCealUreulXluyNR53vLu4y8FAYe2UqO60="
    payload = {}
    print(url)
    response = requests.request("GET", request_url_x_bogus(url), headers=request_header, data=payload)
    try:
        result = json.loads(response.text)
        print(result.get("max_cursor"))
        return result.get("aweme_list"), result.get("max_cursor")
    except Exception as e:
        print(e)


def download(home_url, download_dir, first_load, callback, finish, error):
    try:
        __user_sec_id = home_url.replace("https://www.douyin.com/user/", "")
        if __user_sec_id.__contains__("?"):
            __user_sec_id = __user_sec_id.split("?")[0]
        __cursor = 0
        while True:
            aweme_list, max_cursor = get_user_post(__user_sec_id, __cursor)
            if aweme_list is None or len(aweme_list) <= 0:
                print("没有更多数据了")
                finish()
                break
            if __cursor == 0:
                first_load()
            __cursor = max_cursor
            for aweme_item in aweme_list:
                play_addr_h264 = aweme_item.get("video").get("play_addr_h264")
                play_addr_265 = aweme_item.get("video").get("play_addr_265")
                play_addr = aweme_item.get("video").get("play_addr")
                title = aweme_item.get("desc")
                create_time = aweme_item.get("create_time")
                cover = aweme_item.get("video").get("cover").get("url_list")[0]
                author = aweme_item.get("author").get("nickname")
                aweme_id = aweme_item.get("aweme_id")
                video_url = f"https://www.douyin.com/video/{aweme_id}"
                if play_addr_h264 is not None:
                    download_url = play_addr_h264.get("url_list")[0]
                elif play_addr_265 is not None:
                    download_url = play_addr_265.get("url_list")[0]
                else:
                    download_url = play_addr.get("url_list")[0]
                # 修复视频标题中包含特殊字符导致下载失败问题
                if str(title).__contains__("/"):
                    title = str(title).replace("/", "-")
                if str(title).__contains__("|"):
                    title = str(title).replace("|", "-")
                download_base_dir = os.path.join(download_dir, author)
                if not os.path.exists(download_base_dir):
                    os.makedirs(download_base_dir)
                dist_file_name = download_base_dir + "/" + title + ".mp4"
                if not os.path.exists(dist_file_name):
                    is_download = 0
                else:
                    is_download = 2
                callback({
                    "video_url": video_url,
                    "author": author,
                    "title": title,
                    "cover": cover,
                    "is_download": is_download,  # 0-未下载 1-下载中 2-下载完成
                    "create_at": datetime.datetime.fromtimestamp(create_time).strftime("%Y-%m-%d"),
                    "download_url": download_url,
                })
    except Exception as e:
        error()
